package com.scau.os.course_manager.Clock;

public class Timeout {
    private int delayTime;
    private int intervalTime;
    private Runnable intervalCallback,finishCallback,delayCallback;

    private int cnt=0;

    public Timeout(int delayTime, Runnable delayCallback) {
        this.delayTime = delayTime;
        this.delayCallback = delayCallback;
    }

    public Timeout(int delayTime, Runnable finishCallback, Runnable delayCallback) {
        this.delayTime = delayTime;
        this.finishCallback = finishCallback;
        this.delayCallback = delayCallback;
    }

    public Timeout(int delayTime, int intervalTime, Runnable intervalCallback, Runnable delayCallback) {
        this.delayTime = delayTime;
        this.intervalTime = intervalTime;
        this.intervalCallback = intervalCallback;
        this.delayCallback = delayCallback;
    }

    public void update(){
        cnt++;
        if(delayTime==0||cnt%delayTime==0){
            if(delayCallback!=null){
                delayCallback.run();
                if(intervalCallback!=null){
                    delayCallback=null;
                }
                if(finishCallback!=null&&intervalCallback==null){
                    System.out.println(cnt+" run finishCallback");
                    /**
                     * 注意这里finishCallback要加上里面的run()方法要加上这样一段
                     * tasksToUnRegister.add(new Runnable() {
                     *                     @Override
                     *                     public void run() {
                     *                         tasks.remove(t);
                     *                     }
                     *                 });
                     * 这样才能正确的注销
                     */
                    finishCallback.run();
                    intervalCallback=null;
                }else {
                    System.out.println("FinishTask is null");
                }

            }else if(intervalCallback==null){
                System.out.println("DelayTask is null");
            }

        }
        if(intervalTime==0||cnt%intervalTime==0){
            if(intervalCallback!=null){
                intervalCallback.run();
            }
        }
    }

    public void setFinishCallback(Runnable callback){
        finishCallback=callback;
    }
}
